import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TableBody } from '@/components/ui/table';
import { ResponsiveTable, ResponsiveTableHeader, ResponsiveTableRow, ResponsiveTableHead, ResponsiveTableCell, TableLoading, TableEmpty } from '@/components/ui/responsive-table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Eye, Clock, CheckCircle, XCircle, AlertCircle, Search, Filter, Calendar, User, FileText } from 'lucide-react';

// 模拟审批任务数据
const mockApprovalTasks = [
  {
    id: 1,
    task_code: 'APV-2024-001',
    title: '电商平台开发项目立项申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '张三',
    applicant_department: '技术部',
    submit_time: '2024-01-15 10:30:00',
    deadline: '2026-01-20 18:00:00',
    status: 'pending',
    priority: 'high',
    current_approver: '李四',
    current_role: '部门经理',
    progress: 1,
    total_steps: 3,
    budget: 500000,
    description: '开发一个完整的电商平台，包含用户管理、商品管理、订单管理等功能'
  },
  {
    id: 2,
    task_code: 'APV-2024-002',
    title: '客户管理系统升级项目变更申请',
    type: 'project_change',
    type_name: '项目变更',
    applicant_name: '王五',
    applicant_department: '产品部',
    submit_time: '2024-01-16 14:20:00',
    deadline: '2024-01-22 18:00:00',
    status: 'approved',
    priority: 'medium',
    current_approver: '赵六',
    current_role: '技术总监',
    progress: 3,
    total_steps: 3,
    budget: 200000,
    description: '对现有客户管理系统进行功能升级和性能优化'
  },
  {
    id: 3,
    task_code: 'APV-2024-003',
    title: '移动端APP开发项目验收申请',
    type: 'project_acceptance',
    type_name: '项目验收',
    applicant_name: '钱七',
    applicant_department: '移动端部',
    submit_time: '2024-01-17 09:15:00',
    deadline: '2024-01-25 18:00:00',
    status: 'rejected',
    priority: 'high',
    current_approver: '孙八',
    current_role: '质量总监',
    progress: 2,
    total_steps: 3,
    budget: 800000,
    description: '移动端APP开发完成，申请项目验收'
  },
  {
    id: 4,
    task_code: 'APV-2024-004',
    title: '新员工培训项目立项申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '周九',
    applicant_department: '人力资源部',
    submit_time: '2024-01-18 11:45:00',
    deadline: '2024-01-23 18:00:00',
    status: 'pending',
    priority: 'low',
    current_approver: '吴十',
    current_role: 'HR总监',
    progress: 1,
    total_steps: 2,
    budget: 50000,
    description: '为新入职员工制定培训计划，提升团队技能水平'
  },
  {
    id: 5,
    task_code: 'APV-2024-005',
    title: '数据分析平台建设项目立项申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '陈十一',
    applicant_department: '数据部',
    submit_time: '2024-01-10 08:30:00',
    deadline: '2024-01-15 18:00:00',
    status: 'pending',
    priority: 'high',
    current_approver: '李四',
    current_role: '部门经理',
    progress: 1,
    total_steps: 3,
    budget: 300000,
    description: '构建企业级数据分析平台，提升数据决策能力'
  },
  {
    id: 11,
    task_code: 'APV-2024-011',
    title: '逾期项目：旧系统维护申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '张十七',
    applicant_department: '运维部',
    submit_time: '2024-01-01 09:00:00',
    deadline: '2024-01-05 18:00:00',
    status: 'pending',
    priority: 'high',
    current_approver: '李四',
    current_role: '部门经理',
    progress: 1,
    total_steps: 3,
    budget: 80000,
    description: '旧系统维护申请，已逾期多日'
  },
  {
    id: 12,
    task_code: 'APV-2024-012',
    title: '紧急项目：服务器故障修复申请',
    type: 'project_change',
    type_name: '项目变更',
    applicant_name: '李十八',
    applicant_department: '技术部',
    submit_time: '2024-01-20 14:00:00',
    deadline: '2024-01-21 18:00:00',
    status: 'pending',
    priority: 'high',
    current_approver: '赵六',
    current_role: '技术总监',
    progress: 1,
    total_steps: 2,
    budget: 50000,
    description: '服务器故障修复，需要紧急处理'
  },
  {
    id: 13,
    task_code: 'APV-2024-013',
    title: '即将到期：新功能开发申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '王十九',
    applicant_department: '产品部',
    submit_time: '2024-01-18 10:30:00',
    deadline: '2024-01-22 18:00:00',
    status: 'pending',
    priority: 'medium',
    current_approver: '李四',
    current_role: '部门经理',
    progress: 1,
    total_steps: 3,
    budget: 120000,
    description: '新功能开发申请，即将到期'
  },
  {
    id: 6,
    task_code: 'APV-2024-006',
    title: '网络安全系统升级项目变更申请',
    type: 'project_change',
    type_name: '项目变更',
    applicant_name: '刘十二',
    applicant_department: '安全部',
    submit_time: '2024-01-12 16:45:00',
    deadline: '2024-01-18 18:00:00',
    status: 'returned',
    priority: 'high',
    current_approver: '赵六',
    current_role: '技术总监',
    progress: 1,
    total_steps: 3,
    budget: 150000,
    description: '升级网络安全系统，增强防护能力'
  },
  {
    id: 7,
    task_code: 'APV-2024-007',
    title: '客户关系管理系统验收申请',
    type: 'project_acceptance',
    type_name: '项目验收',
    applicant_name: '孙十三',
    applicant_department: '销售部',
    submit_time: '2024-01-08 14:20:00',
    deadline: '2024-01-12 18:00:00',
    status: 'approved',
    priority: 'medium',
    current_approver: '孙八',
    current_role: '质量总监',
    progress: 3,
    total_steps: 3,
    budget: 400000,
    description: '客户关系管理系统开发完成，申请验收'
  },
  {
    id: 8,
    task_code: 'APV-2024-008',
    title: '办公自动化系统立项申请',
    type: 'project_approval',
    type_name: '项目立项',
    applicant_name: '吴十四',
    applicant_department: '行政部',
    submit_time: '2024-01-05 09:15:00',
    deadline: '2024-01-10 18:00:00',
    status: 'rejected',
    priority: 'low',
    current_approver: '李四',
    current_role: '部门经理',
    progress: 2,
    total_steps: 3,
    budget: 100000,
    description: '建设办公自动化系统，提升工作效率'
  },
  {
    id: 9,
    task_code: 'APV-2024-009',
    title: '财务管理系统升级变更申请',
    type: 'project_change',
    type_name: '项目变更',
    applicant_name: '郑十五',
    applicant_department: '财务部',
    submit_time: '2024-01-03 11:30:00',
    deadline: '2024-01-08 18:00:00',
    status: 'pending',
    priority: 'medium',
    current_approver: '赵六',
    current_role: '技术总监',
    progress: 1,
    total_steps: 2,
    budget: 250000,
    description: '升级财务管理系统，增加新功能模块'
  },
  {
    id: 10,
    task_code: 'APV-2024-010',
    title: '人力资源管理系统验收申请',
    type: 'project_acceptance',
    type_name: '项目验收',
    applicant_name: '王十六',
    applicant_department: '人力资源部',
    submit_time: '2024-01-01 10:00:00',
    deadline: '2024-01-05 18:00:00',
    status: 'approved',
    priority: 'medium',
    current_approver: '孙八',
    current_role: '质量总监',
    progress: 3,
    total_steps: 3,
    budget: 350000,
    description: '人力资源管理系统开发完成，申请验收'
  }
];

const ApprovalTaskList = ({ onView, onApprove, onReject, onReturn, userRole = 'user', defaultStatusFilter = 'ALL' }) => {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState(defaultStatusFilter);
  const [typeFilter, setTypeFilter] = useState('ALL');
  const [priorityFilter, setPriorityFilter] = useState('ALL');

  // 获取审批任务列表
  const fetchApprovalTasks = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      setTasks(mockApprovalTasks);
    } catch (error) {
      console.error('获取审批任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 过滤任务
  const filteredTasks = tasks.filter(task => {
    const matchesSearch = searchKeyword === '' || 
                         task.title.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         task.task_code.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         task.applicant_name.toLowerCase().includes(searchKeyword.toLowerCase());
    const matchesStatus = statusFilter === 'ALL' || task.status === statusFilter;
    const matchesType = typeFilter === 'ALL' || task.type === typeFilter;
    const matchesPriority = priorityFilter === 'ALL' || task.priority === priorityFilter;

    return matchesSearch && matchesStatus && matchesType && matchesPriority;
  });

  // 获取状态徽章样式
  const getStatusBadgeVariant = (status) => {
    switch (status) {
      case 'pending': return 'default';
      case 'approved': return 'success';
      case 'rejected': return 'destructive';
      case 'returned': return 'secondary';
      default: return 'outline';
    }
  };

  // 获取优先级徽章样式
  const getPriorityBadgeVariant = (priority) => {
    switch (priority) {
      case 'high': return 'destructive';
      case 'medium': return 'default';
      case 'low': return 'secondary';
      default: return 'secondary';
    }
  };

  // 获取状态图标
  const getStatusIcon = (status) => {
    switch (status) {
      case 'pending': return <Clock className="size-4" />;
      case 'approved': return <CheckCircle className="size-4" />;
      case 'rejected': return <XCircle className="size-4" />;
      case 'returned': return <AlertCircle className="size-4" />;
      default: return <Clock className="size-4" />;
    }
  };

  // 计算任务紧急程度
  const getTaskUrgency = (task) => {
    const now = new Date();
    const deadline = new Date(task.deadline);
    const hoursLeft = (deadline - now) / (1000 * 60 * 60);
    
    // 调试信息
    console.log(`任务 ${task.task_code}: 截止时间 ${task.deadline}, 剩余 ${hoursLeft.toFixed(1)} 小时`);
    
    if (hoursLeft < 0) return 'overdue';
    if (hoursLeft < 24) return 'urgent';
    if (hoursLeft < 72) return 'soon';
    return 'normal';
  };

  // 获取紧急程度徽章样式
  const getUrgencyBadgeVariant = (urgency) => {
    switch (urgency) {
      case 'overdue': return 'destructive';
      case 'urgent': return 'default';
      case 'soon': return 'secondary';
      default: return 'outline';
    }
  };

  // 获取紧急程度文本
  const getUrgencyText = (urgency) => {
    switch (urgency) {
      case 'overdue': return '已逾期';
      case 'urgent': return '紧急';
      case 'soon': return '即将到期';
      default: return '';
    }
  };

  useEffect(() => {
    fetchApprovalTasks();
  }, []);

  return (
    <Card>
      <CardHeader>
        <CardTitle>审批任务</CardTitle>
      </CardHeader>
      <CardContent>
        {/* 搜索和筛选 */}
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground size-4" />
              <Input
                placeholder="搜索任务标题、编号或申请人..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <div className="flex gap-2">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部状态</SelectItem>
                <SelectItem value="pending">待审批</SelectItem>
                <SelectItem value="approved">已通过</SelectItem>
                <SelectItem value="rejected">已拒绝</SelectItem>
                <SelectItem value="returned">已退回</SelectItem>
              </SelectContent>
            </Select>
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部类型</SelectItem>
                <SelectItem value="project_approval">项目立项</SelectItem>
                <SelectItem value="project_change">项目变更</SelectItem>
                <SelectItem value="project_acceptance">项目验收</SelectItem>
              </SelectContent>
            </Select>
            <Select value={priorityFilter} onValueChange={setPriorityFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="优先级" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部优先级</SelectItem>
                <SelectItem value="high">高</SelectItem>
                <SelectItem value="medium">中</SelectItem>
                <SelectItem value="low">低</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* 审批任务表格 */}
        <ResponsiveTable>
          <ResponsiveTableHeader>
            <ResponsiveTableRow>
              <ResponsiveTableHead width="24">任务编号</ResponsiveTableHead>
              <ResponsiveTableHead minWidth="32">任务标题</ResponsiveTableHead>
              <ResponsiveTableHead width="20">申请类型</ResponsiveTableHead>
              <ResponsiveTableHead width="20">申请人</ResponsiveTableHead>
              <ResponsiveTableHead width="20">状态</ResponsiveTableHead>
              <ResponsiveTableHead width="20">优先级</ResponsiveTableHead>
              <ResponsiveTableHead width="24">进度</ResponsiveTableHead>
              <ResponsiveTableHead hideOnMobile width="28">提交时间</ResponsiveTableHead>
              <ResponsiveTableHead hideOnMobile width="28">截止时间</ResponsiveTableHead>
              <ResponsiveTableHead hideOnTablet width="24">预算</ResponsiveTableHead>
              <ResponsiveTableHead width="24">操作</ResponsiveTableHead>
            </ResponsiveTableRow>
          </ResponsiveTableHeader>
          <TableBody>
            {loading ? (
              <TableLoading colSpan={11} />
            ) : filteredTasks.length === 0 ? (
              <TableEmpty colSpan={11} message="暂无审批任务" />
            ) : (
              filteredTasks.map(task => {
                const urgency = getTaskUrgency(task);
                return (
                  <ResponsiveTableRow 
                    key={task.id} 
                    className={urgency === 'overdue' ? 'bg-destructive/5' : ''}
                  >
                    <ResponsiveTableCell className="font-mono text-sm" truncate title={task.task_code}>
                      {task.task_code}
                    </ResponsiveTableCell>
                    <ResponsiveTableCell className="font-medium">
                      <div className="flex items-center gap-2 min-w-0">
                        <span className="truncate" title={task.title}>
                          {task.title}
                        </span>
                        {urgency !== 'normal' && (
                          <Badge variant={getUrgencyBadgeVariant(urgency)} className="text-xs flex-shrink-0">
                            {getUrgencyText(urgency)}
                          </Badge>
                        )}
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Badge variant="outline" className="text-xs">
                        {task.type_name}
                      </Badge>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-1">
                        <User className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.applicant_name}>
                          {task.applicant_name}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-1">
                        {getStatusIcon(task.status)}
                        <Badge variant={getStatusBadgeVariant(task.status)} className="text-xs">
                          {task.status === 'pending' ? '待审批' : 
                           task.status === 'approved' ? '已通过' :
                           task.status === 'rejected' ? '已拒绝' : '已退回'}
                        </Badge>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Badge variant={getPriorityBadgeVariant(task.priority)} className="text-xs">
                        {task.priority === 'high' ? '高' : 
                         task.priority === 'medium' ? '中' : '低'}
                      </Badge>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-2">
                        <div className="w-12 bg-secondary rounded-full h-2 flex-shrink-0">
                          <div 
                            className="bg-primary h-2 rounded-full transition-all"
                            style={{ width: `${(task.progress / task.total_steps) * 100}%` }}
                          />
                        </div>
                        <span className="text-xs text-muted-foreground flex-shrink-0">
                          {task.progress}/{task.total_steps}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile className="text-xs">
                      <div className="flex items-center gap-1">
                        <Calendar className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.submit_time}>
                          {task.submit_time}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile className="text-xs">
                      <div className="flex items-center gap-1">
                        <Calendar className="size-3 text-muted-foreground flex-shrink-0" />
                        <span className="truncate" title={task.deadline}>
                          {task.deadline}
                        </span>
                      </div>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnTablet className="text-xs">
                      <span className="truncate block" title={`¥${task.budget?.toLocaleString()}`}>
                        ¥{task.budget?.toLocaleString()}
                      </span>
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-1">
                        <Button 
                          variant="ghost" 
                          size="sm"
                          onClick={() => onView && onView(task)}
                          className="h-8 w-8 p-0"
                        >
                          <Eye className="size-3" />
                        </Button>
                        {task.status === 'pending' && userRole === 'approver' && (
                          <>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => onApprove && onApprove(task)}
                              className="h-8 w-8 p-0 text-green-600 hover:text-green-700"
                            >
                              <CheckCircle className="size-3" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => onReject && onReject(task)}
                              className="h-8 w-8 p-0 text-red-600 hover:text-red-700"
                            >
                              <XCircle className="size-3" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => onReturn && onReturn(task)}
                              className="h-8 w-8 p-0 text-orange-600 hover:text-orange-700"
                            >
                              <AlertCircle className="size-3" />
                            </Button>
                          </>
                        )}
                      </div>
                    </ResponsiveTableCell>
                  </ResponsiveTableRow>
                );
              })
            )}
          </TableBody>
        </ResponsiveTable>
      </CardContent>
    </Card>
  );
};

export default ApprovalTaskList; 